package fr.utbm.lo54.web;

import java.util.ArrayList;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import fr.utbm.lo54.domain.Client;
import fr.utbm.lo54.domain.Session;

@RequestMapping("/public/subscribe")
@Controller
public class SubscribeController {
	@RequestMapping(method = RequestMethod.GET, value = "/{id}")
    public String get(@PathVariable Long id, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
		if (id == null) throw new IllegalArgumentException("An Identifier is required");
    	Session session = Session.findSession(id);
    	modelMap.addAttribute("session", session);
    	return "public/subscribe/index";
    }
    /*@RequestMapping(method = RequestMethod.POST, value = "{id}")
    public void post(@PathVariable Long id, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
    	System.out.println(id);
    }*/

	@ModelAttribute("client")
	public Client getClient(){
		return new Client();
	}
	
	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
	public String subscribeClient(@Valid Client client, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
		 if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, client);
            return "public/subscribe/index";
        }
        client.persist();
        System.out.println("Client ajouté");
        uiModel.addAttribute("session", client.getSession());
        return "public/subscribe/confirm";
	}

    private void populateEditForm(Model uiModel, Client client) {
        //uiModel.addAttribute("client", client);
        uiModel.addAttribute("session", client.getSession());
    }
    
}


